#include "ws.h"

void TOB::UI_WS::run() {
  // Define ui
  UIMenu menum(0, 1, config.offsetX, 0);
  UIBrowser browserb(config.offsetX, 2, 0, 0, config.ws_code);
  UIText addresst(config.offsetX, 1, 0, 1); 
  UIWindow statusw(0, 0, 0, 1);
  
  // Assign temp objects
  this->browserb = &browserb;
  this->addresst = &addresst;
  this->statusw = &statusw;

  // Go to page
  std::function<void()> go = [&](){
    std::string test;
    WS::Data data((int8*)test.c_str(), test.size());
    WS::Client client = WS::Client(config.nsip, config.username, config.password);
    //WS::Client client = WS::Client(1 << 24 | 127, "root", "123456");

    std::string msg;
    try {
      client.request(CONVERT(addresst.lines[0]), data);
      msg = data.getData();
      browserb.setPage(msg);
    } catch(WS::ClientException e) {
      msg = e.getMessage();
      browserb.setPage(msg);
    }

    browserb.focus();
    menum.showCursor(false);
  };

  menum.insert(config.lang["back"], [&](){ 
    menum.running = false; 
  });

  menum.insert(config.lang["browser-address"], [&](){
    addresst.focus();
    go();
  });

  menum.insert(config.lang["browser-go"], go);

  addresst.eventTab = [&]() {
    addresst.running = false;
  };

  browserb.eventLink = [&](std::string &link) {
    addresst.lines[0] = CONVERT(link);
    addresst.printLine();
    go();
  };

  String str;
  status(str);
  menum.focus();
}


void TOB::UI_WS::status(String &msg) {
  statusw->setCursor(0, 0);
  statusw->clearLine();
  statusw->setColor(Color::Title);
  String out = config.lang["browser"] + msg;
  statusw->putString(out);
}
